package person.twj.storageservice.feign.client;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import person.twj.storageservice.entity.StorageTbl;
import person.twj.storageservice.service.IStorageTblService;
import person.twj.common.feign.StorageFeignService;

@Slf4j
@RestController
@RequestMapping("/storage")
public class StorageServiceImpl implements StorageFeignService {

    @Autowired
    private IStorageTblService iStorageTblService;
    @Override
    @GetMapping(value = "/storage/{commodityCode}/{count}", produces = "application/json")
    @GlobalTransactional
    public String storage(@PathVariable("commodityCode") String commodityCode,
                          @PathVariable("count") int count,
                          @RequestParam("type") int type) {
        // 库存-count
        log.info("Storage Service Begin ... xid: " + RootContext.getXID());
        StorageTbl storage = iStorageTblService.getById("1");
        log.info("原始storage: " + JSON.toJSONString(storage));
        UpdateWrapper wrapper = new UpdateWrapper();
        wrapper.setSql("count = count - {0} where commodity_code = {1}",
                count, commodityCode );

        boolean result = iStorageTblService.update(wrapper);
        log.info("Storage Service End ... ");
        if(type==3){
            throw new RuntimeException("type=3");
        }
        if (result ) {
            return "SUCCESS";
        }
        return "FAIL";
    }
}
